from django.http import HttpResponse
from rest_framework.decorators import api_view
import requests
import json


# Create your views here.

@api_view(['GET', 'POST'])
def list(request):
    keywords = request.GET['keywords']
    check_in = request.GET['check_in']  # 20210115
    check_out = request.GET['check_out']
    offset = request.GET['offset']
    city_id = request.GET['city_id']
    html = requests.get(
        f'https://ihotel.meituan.com/hbsearch/HotelSearch?utm_medium=touch&version_name=999.9&platformid=1&cateId=20&newcate=1&limit=20&offset={offset}&cityId={city_id}&ci={city_id}&startDay={check_in}&endDay={check_out}&q={keywords}&ste=_b300202&mypos=30.66874%2C104.086667&attr_28=129&sort=defaults'
    )
    json_data = json.loads(html.text)
    data_list = json_data['data']['searchresult']
    lists = []
    for data in data_list:
        poiid = data['poiid']
        addr = data['addr']
        name = data['name']
        lat = data['lat']
        lng = data['lng']
        city_name = data['cityName']
        city_id = data['cityId']
        scoreintro = data['scoreIntro']
        lists.append({'poiid': poiid, 'addr': addr, 'name': name, 'lat': lat, 'lng': lng, 'city_name': city_name,
                      'city_id': city_id,
                      'scoreintro': scoreintro})


    data = {
        'code': 200,
        'list': [list for list in lists]
    }

    return HttpResponse(json.dumps(data))


import time
from datetime import datetime


# 毫秒时间戳
def stime(stime):
    datetime_obj = datetime.strptime(stime, "%Y-%m-%d")
    obj_stamp = int(time.mktime(datetime_obj.timetuple()) * 1000.0 + datetime_obj.microsecond / 1000.0)
    return obj_stamp


# 美团价格
def hotel_price(request):
    check_in = request.GET.get('check_in')  # 按照此格式 2021-01-12
    check_out = request.GET.get('check_out')
    hotel_id = request.GET.get('hotel_id')
    start = stime(check_in)
    end = stime(check_out)
    html = requests.get(
        f'https://ihotel.meituan.com/group/v1/yf/list/{hotel_id}?&start={start}&end={end}')
    json_data = json.loads(html.text)
    json_list = json_data['data']['result']
    hotels = []
    for list in json_list:
        goodsId = list['goodsId']
        goodsName = list['goodsName']
        cancelRule = list['cancelRule']
        originalPrice = list['originalPrice']
        roomdesc = list['extInfo']['roomDesc']
        fullRoomDesc = list['fullRoomDesc']

        hotels.append({
            'goods_id': goodsId, 'goods_name': goodsName, 'cancel_rule': cancelRule,
            'original_price': originalPrice / 100,
            'room_desc': roomdesc, 'full_roomd_esc': fullRoomDesc
        })



    json_data = {
        'code': 200,
        'hotel': [hotel for hotel in hotels]
    }

    return HttpResponse(json.dumps(json_data))
